/* eslint-disable */
import { insertMoment,nextTick,insertJQuery } from '../../lib/utils.js';
import { viewSbxml_yhs,getQueryString,sendSbList } from './tool.js'
import { saveTable,sendTableDetail } from './asyncTable.js'
import {handleSmallStep1,handleSmallStep2} from './smallZeroReport.js'
import { asyncSetInterval,fixZeroInfo } from "../../lib/zeroReportUtils.js";
import { cwbbReport } from './cwbbReport.js'

const pages={
  "index":"/bszm-web/apps/views/publicPage/desk.html",
  "reportIndex":"/bszm-web/apps/views/openWin/ysbtc.html",
  "step1":"/sbzx-web/apps/views/sb_ybnsr_201905/sb_ybnsr.html?sbzlDm=10101",
  "smallStep1":"/sbzx-web/apps/views/xgmsb-tbs_2019/xgmsb-tbs.html?sbzlDm=10102",
  "stepGetTable":"/yhs-web/cxzx/index.html",
  "stepSaveTable":"/yhs-web/api/sbcx/getSbbmx",
  "qsReport": "/sbzx-web/apps/views/sb_sdsA_yj_new_202006/sb_sdsA_yj_new.html",
  "reportResult": "/sbzx-web/apps/views/sbjgcx/sbjgcx.html",
  cwbbPage: '/sbzx-web/apps/views/sb_cwbb_xqy_kjzz/sb_cwbb_xqy_kjzz.html'
};

const isPage=(name)=>{
  return window.location.href.includes(pages[name])
}

let currentZeroInfo;

const startZeroReport = async (data) => {
  console.log(data.data.currentZeroInfo);
  window.sessionStorage.setItem('isZero',true);
  if (window.location.href.includes('https://etax.sichuan.chinatax.gov.cn/bszm-web/apps/views/beforeLogin/indexBefore/pageIndex.html')) {
    handleLogin(data.data.currentZeroInfo);
  }
  currentZeroInfo=data.data.currentZeroInfo;
};



const handleLogin=(info)=>{
  console.log(info);
  if (info.zzsType === "小规模纳税人") {
    window.sessionStorage.setItem("isSmall", true);
  }
  nextTick(()=>{
    if(window.goLogin){
      window.goLogin();
      nextTick(()=>{
        let userName=$("#userName"),password=$("#passWord");
        userName.closest("section").append(info.nationalTaxUser+"<br/>");
        password.closest("section").append(info.nationalTaxPass);
        return true;
      },500);
      return true;
    }
  },500)
};



const handleReportIndex = (info) => {
  console.log('currentZeroInfo',info);
  asyncSetInterval(()=>{
    let lis =  $('#sbcontent > li');
    function getMonth(m){
      let month = +m < 10 ? `0${m}` : `${m}`
      return month
    }
    let recordList = Array.from(lis).map(item => {
      let declareName = $(item).find('span:eq(0)').text();
      let isSuccess = $(item).find('span:eq(1)').text() === "未申报" ? false : true;
      let accountBook = info.year + '-' + getMonth(info.endPeriod);
      let declareCycle = "month";
      declareName.includes('年') ? declareCycle = "year" : '';
      declareName.includes('季') ? declareCycle = "season" : '';
      return {
        declareName,
        accountBook,
        declareCycle,
        isSuccess,
      };
    })
    if (info.recordList.length < recordList.length) {
      fixZeroInfo({recordList});
      setTimeout(()=>{
        window.location.reload();
      },500)
    }else{
      let xgmData = findInfoRow(info,"增值税小规模纳税人"); //currentZeroInfo种的数据
      let qsData = findInfoRow(info,"居民企业所得税月（季）度预缴纳税申报（A类）");
      let cwbbData = findInfoRow(info,"财务报告报送与信息采集");
      let xgm = findRow("增值税小规模纳税人") // 页面种的列表元素
      let qs = findRow('居民企业所得税月（季）度预缴纳税申报（A类）');
      let cwbb = findRow('财务报告报送与信息采集（小企业会计准则）（月季报）');

      

      if (cwbbData && !cwbbData.isSuccess) {
        let btn = cwbb.find('.dbBtn');
        let isSuccess = cwbb.find('span:eq(1)').text() === "未申报" ? false : true;
        if(isSuccess) {
          cwbbData.isSuccess = isSuccess;
          fixZeroInfo({recordList: [cwbbData]});
          window.location.reload();
          return true;
        }
        if (btn.length) {
          window.open(btn.attr('href'));
          setTimeout(() => {
            window.close();
          }, 1000);
          return true;
        }
      }

      if (xgmData && !xgmData.isSuccess) {
        let btn = xgm.find('.dbBtn');
        if (btn.length) {
          window.open(btn.attr('href'));
          window.close();
          return true;
        }
      }
      
      if (qsData && !qsData.isSuccess) {
        let btn = qs.find('.dbBtn');
        if (btn.length) {
          window.open(btn.attr('href'));
          window.close();
          return true;
        }
      }
      

      // let isAllSuccess = info.recordList.every(item => item.isSuccess);
      function isAllSuccess(){
        let xgmData = findInfoRow(info,"增值税小规模纳税人");
        let qsData = findInfoRow(info,"居民企业所得税月（季）度预缴纳税申报（A类）");
        let cwbbData = findInfoRow(info,"财务报告报送与信息采集");
        let reportCategory = [xgmData,qsData,cwbbData].filter(Boolean);
        let res = reportCategory.every(item => item.isSuccess);
        return res;
      }

      if(isAllSuccess()){
        insertMoment()
        asyncSetInterval(()=>{
          if(window.moment){
            $.ajax({
              url: 'https://etax.sichuan.chinatax.gov.cn/yhs-web/api/sbcx/querySbjgxx',
              type: 'POST',
              contentType : "application/json;charset=UTF-8",
              data: JSON.stringify({sbrqQ:window.moment().format("YYYY-MM-01"),sbrqZ:window.moment().add(1,"month").format("YYYY-MM-01"),zsxmDm:"",yzpzzlDm:"",sssqQ:"",sssqZ:""}),
              success: function(data) {
                if(data && data.value && data.value.length){
                  data.value.forEach(item=>{
                    let url="https://etax.sichuan.chinatax.gov.cn/yhs-web/api/sbcx/getSbbmx?sbuuid="+item.sbuuid+"&gdsBz="+item.gdsBz+"&pzxh="+item.pzxh+"&sbxh="+item.sbxh+"&sssqQ="+item.sssqQ+"&sssqZ="+item.sssqZ+"&sbzlDm="+item.sbzlDm+"&bbidDm=001&isSssb="+item.isSssb;
                    console.log(url)
                    window.open(url);
                  });
                  setTimeout(()=>{
                    // sendSbList();
                    window.postMessage(
                      {
                        event: "zeroReportBack",
                        data: { ...info },
                      },
                      "*"
                    );
                  },10000);
                }
              }
            });
          }
          return true;
        },2000)
      }
    }
    return true;
  },1000)
}

const closePop = async () => {
  let msgBox = $(".mini-messagebox");
  if (!msgBox.length) {
    return true;
  }
  await asyncSetInterval(()=>{
    let closeBtn = msgBox.find('.mini-tools-close');
    if(closeBtn.length) {
      closeBtn.click();
    }
    return true;
  },500)
  closePop();
}

const handleReportResult = async (info) => {
  console.log('info',info)
  await asyncSetInterval(()=>{
    let queryBtn = $('#search-btn')
    if (queryBtn.length) {
      queryBtn.click();
    }
    return true;
  },1000)
  await asyncSetInterval(()=>{
    let lis = $('#mini-grid-table-bodysbjgcx_grid .mini-grid-row');
    lis = Array.from(lis).filter(item => $(item).text().includes("申报成功"));
    let recordList = lis.map(item => {
      let categoryTxt = $(item).find('td:eq(1)').text();
      let isSuccess = $(item).find('td:eq(6)').text() === "申报成功" ? true : false;
      let preData = $(item).find('td:eq(4)').text().split('-')[1]
      let endData = $(item).find('td:eq(5)').text().split('-')[1]
      let month = endData - preData;
      let declareCycle = month === 11 ? "year" : month === 2 ? "season" : "month";
      if (categoryTxt.includes('小规模')) {
        return {
          declareName: "增值税小规模纳税人",
          declareCycle,
          isSuccess,
        }
      }
      if (categoryTxt.includes("企业所得税")) {
        return {
          declareName: "居民企业所得税月（季）度预缴纳税申报（A类）",
          declareCycle,
          isSuccess,
        }
      }
    }).filter(Boolean)
    console.log('recordList',recordList);
    fixZeroInfo({recordList})
    return true;
  },3000).then(()=>{ // 结果页同步recordList信息后回到 应申报页面 继续申报其他税种
    setTimeout(() => {
      window.location.href = pages.reportIndex;
    }, 1000);
  })
}

const handleQsReport = async (info) => {
  closePop();
  asyncSetInterval(async ()=>{
    let tabs = $('#tabs > table > tbody > tr > td:nth-child(2) > div.mini-tabs-scrollCt > div.mini-tabs-headers > table > tbody > tr > .mini-tab');
    for(let i=0; i < tabs.length; i++){
      await asyncSetInterval(()=>{
        tabs[i].click();
        return true;
      },500)
    }
    tabs[0].click();
    await asyncSetInterval(()=>{
      $('#gxjs input:eq(1)').click();
      $('#kjxqy input:eq(1)').click();
      $('#jsdy input:eq(1)').click();
      $(".mini-tabs-bodys > .mini-tabs-body:nth-child(1) .sb_table > tbody > tr:nth-child(6) > td.enable:eq(-1) > input").val(1);
      $(".mini-tabs-bodys > .mini-tabs-body:nth-child(1) .sb_table > tbody > tr:nth-child(6) > td.enable:eq(-2) > input").val(1);
      let endSeason = $(".mini-tabs-bodys > .mini-tabs-body:nth-child(1) .sb_table > tbody > tr:nth-child(7) > td.enable:eq(-1) > input");
      let startSeason = $(".mini-tabs-bodys > .mini-tabs-body:nth-child(1) .sb_table > tbody > tr:nth-child(7) > td.enable:eq(-2) > input");
      startSeason.val(parseFloat(info.quarterSum / 10000) || 0.01);
      endSeason.val(parseFloat(info.endSum / 10000) || 0.01);
      return true;
    },500)
    await asyncSetInterval(()=>{
      $("#sb_save").click();
      return true;
    },500)
    await asyncSetInterval(()=>{
      let msgBox = $(".mini-messagebox");
      if (msgBox.length) {
        msgBox.find(".mini-button:eq(0)")[0].click();
      }
      return true;
    },500)
    await asyncSetInterval(()=>{
      let msgBox = $(".mini-messagebox");
      if (msgBox.length) {
        msgBox.find(".mini-button:eq(0)")[0].click();
      }
      return true;
    },500)
    await asyncSetInterval(()=>{
      let msgBox = $(".mini-messagebox");
      if (msgBox.length) {
        msgBox.find(".mini-button:eq(0)")[0].click();
      }
      return true;
    },2000)
    return true;
  },4000)
}

const findInfoRow = (info,text) => {
  return info.recordList.find(
    (item) => item.declareName.includes(text)
  )
}

const findRow=(word)=>{
  let lis =  $('#sbcontent > li'),result;
  lis.each((index,item)=>{
    let span=$("span.txt-l",item);
    if(span.length && span.html()===word){
      console.log($(item).html(),index);
      result=$("#sbcontent .wsdbLi:eq("+index+")");
    }
  })
  return result;
}

const handleIndex=(isSmall)=>{
  asyncSetInterval(()=>{
    let tcyw = $('#left-menu > div.menu-div.menu-tcyw > ul > li > a');
    let ysbtc =  Array.from(tcyw).find(item => $(item).text().includes('应申报套餐'))
    if (ysbtc) {
      window.location.href =  $(ysbtc).attr('data-url');
      return true;
    }
  },1000);
  // window.setTimeout(()=>{
  //   window.location.reload();
  // },5000)

};

const handleStep1=()=>{
  const saveTable2=()=>{
    let btn=$('[data-bbid="003"] .sb_edit:visible');
    if(btn.length){
      btn.click();
      nextTick(()=>{
        let minWin=$(".mini-window");
        if(minWin.length){
          let loadingMask=$(".mini-mask-loading",minWin);
          if(!loadingMask.length){
            let win=$("iframe",minWin)[0].contentWindow;
            if(win && win.$ && win.$("#sb_save").length){
              win.$("#sb_save").click();
              nextTick(()=>{
                if(win.$(".mini-panel-border .mini-button").length){
                  win.$(".mini-panel-border .mini-button").click();
                  setTimeout(()=>{
                    saveTable1();
                  },500);
                  return true;
                }
              });
              return true;
            }

          }
        }
      });
    }else{
      saveTable1();
    }
  };

  const saveTable1=()=>{
    let btn=$('[data-bbid="002"] .sb_edit:visible');
    if(btn.length){
      btn.click();
      nextTick(()=>{
        let minWin=$(".mini-window");
        if(minWin.length){
          let loadingMask=$(".mini-mask-loading",minWin);
          if(!loadingMask.length){
            let win=$("iframe",minWin)[0].contentWindow;
            if(win && win.$ && win.$("#sb_save").length){
              win.$("#sb_save").click();
              nextTick(()=>{
                if(win.$(".mini-panel-border .mini-button").length){
                  win.$(".mini-panel-border .mini-button").click();
                  setTimeout(()=>{
                    saveTableMain();
                  },500)
                  return true;
                }
              });
              return true;
            }

          }
        }
      });
    }else{
      saveTableMain();
    }
  };

  const saveTableMain=()=>{
    let btn=$('[data-bbid="001"] .sb_edit:visible');
    if(btn.length){
      btn.click();
      nextTick(()=>{
        let minWin=$(".mini-window");
        if(minWin.length){
          let loadingMask=$(".mini-mask-loading",minWin);
          if(!loadingMask.length){
            let win=$("iframe",minWin)[0].contentWindow;
            if(win && win.$ && win.$("#sb_save").length){
              win.$("#sb_save").click();
              nextTick(()=>{
                if(win.$(".mini-panel-border .mini-button").length){
                  win.$(".mini-panel-border .mini-button").click();
                  setTimeout(()=>{
                    submitSb();
                  },500);
                  return true;
                }
              });
              return true;
            }

          }
        }
      });
    }else{
      submitSb();
    }
  };

  const submitSb=()=>{
    nextTick(()=>{
      if($("#sb_save").length){
        $("#sb_save").click();
        nextTick(()=>{
          let btn=$(".mini-panel-border .mini-button:eq(0)");
          if(btn.length && btn.html().includes("确定")){
            btn.click();
            nextTick(()=>{
              let btn=$(".mini-panel-border .mini-button:eq(0)");
              if(btn.length && btn.html().includes("确定")){
                btn.click();
                return true;
              }
            },500);
            return true;
          }
        },500);
        return true;
      }
    })
  };

  setTimeout(()=>{
    if($("#closeZcTip").length){
      $("#closeZcTip").click();
    }
    setTimeout(()=>{
      saveTable2();
    },500)
  },1000)

};

const handleGetTable=()=>{
  let $=window.jQuery;
  const findTr=(word)=>{
    let trs=$(".ant-table-body tr"),tr;
    trs.each((idx,item)=>{
      let td=$("td:eq(1)",item);
      console.log(td);
      if(td.length && td.html().includes(word)){
        tr=item;
      }
    });
    return tr;
  };
  nextTick(()=>{
    if($(".ant-form-item .ant-select-selection:eq(0)").length){
      $(".ant-form-item .ant-select-selection:eq(0)").click();
      setTimeout(()=>{
        $(".ant-select-dropdown li:eq(0)").click();
        setTimeout(()=>{
          $(".ant-btn-primary:eq(0)").click();
        },500)
      },500);
      return true;
    }
  },2000)
};

const handleSaveTable=()=>{
  //saveTable
  insertJQuery();
  nextTick(()=>{
    if(window.jQuery){
      let $=window.jQuery,html="<div>",sbzlDm=getQueryString("sbzlDm");
      let types={
        "10115":"城建税、教育费附加、地方教育附加税（费）申报表",
        "10101":"增值税纳税申报表",
        "10103":"增值税小规模纳税人",
        "10442":"居民企业所得税月（季）度预缴纳税申报（A类）"
      };

      $("table").each((idx,item)=>{
        html+=$(item).html();
      })
      html+="</div>";
      if(types[sbzlDm]){
        saveTable(types[sbzlDm],html);
      }
      setTimeout(()=>{
        window.close();
      },1000);
      return true;
    }
  },500)
};

const checkZeroReport = ()=>{
  nextTick(()=>{
    if(currentZeroInfo) {
      // let isZero=window.sessionStorage.getItem("isZero"),isSmall=window.sessionStorage.getItem("isSmall") || "true";
      // console.log(currentZeroInfo,isZero,isSmall);
      // if(isZero!=="true"){
      //   return true;
      // }

      if (isPage("index")) {
        handleIndex();
        return true;
      }

      if (isPage('reportIndex')) { // 本月应申报页面
        handleReportIndex(currentZeroInfo);
        return true;
      }

      if (isPage('cwbbPage')) {
        cwbbReport(currentZeroInfo);
      }

      if (isPage("step1")) {
        handleStep1();
        return true;
      }

      if(isPage("stepSaveTable")){ // 缓存报表
        handleSaveTable();
        return true;
      }

      if(isPage("smallStep1")){ // 小规模申报流程
        handleSmallStep1();
        return true;
      }
      
      if (isPage('qsReport')) { // 企税申报流程
        handleQsReport(currentZeroInfo);
        return true;
      }

      if (isPage('reportResult')) { // 申报结果页
        handleReportResult(currentZeroInfo);
        return true;
      }

      return true;
    }
  })
}


export {
  startZeroReport,
  checkZeroReport
};
